package com.chinacoal.microservice.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.CcmsSmartleasingTenantMapper;
import com.chinacoal.microservice.pojo.CcmsSmartleasingTenant;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.TenantManagementService;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 运维模块-租户管理-后端实现类
 * @date 2020-11-18 14：36
 */
@Slf4j
@Service
public class TenantManagementServiceImpl implements TenantManagementService {
    @Autowired
    private CcmsSmartleasingTenantMapper tenantMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Description: 查询所有的租户信息（带分页）
     * @author zhuliang
     * @date 2020/11/18 14:40
     */
    @Override
    public Result<List<CcmsSmartleasingTenant>> getAllTenant(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingTenant> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页查询
        List<CcmsSmartleasingTenant> tenantAllByPage = tenantMapper.getAllByPage(toPage, currency.getProperty(), currency.getManagementOffice());

        return Result.success(tenantAllByPage, toPage.getTotal());
    }

    /**
     * @Description: 根据租户id查询对应的租户信息
     * @author zhuliang
     * @date 2020/11/18 17:15
     */
    @Override
    public Result<CcmsSmartleasingTenant> getTenantById(String pkTenantId, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根据id查询
        CcmsSmartleasingTenant tenant = tenantMapper.getAllByTenantId(pkTenantId, currency.getProperty(), currency.getManagementOffice());

        //拆分地址
        if (null != tenant) {
            if (StringUtils.isNotBlank(tenant.getFkUpPhotoId())) {
                tenant.setFkUpPhotoIdList(tenant.getFkUpPhotoId().split(","));
            }
        } else {
            log.error(CodeMsg.NOT_FOUND.toString() + "-->此租户信息无权限访问，或数据丢失-->" + pkTenantId);
            return Result.error(CodeMsg.NOT_FOUND);
        }


        return Result.success(tenant);
    }

    /**
     * @Description: 修改租户信息
     * @author zhuliang
     * @date 2020/11/18 17:19
     */
    @Override
    public Result updateTenant(CcmsSmartleasingTenant tenant, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //修改租户信息的信息
        tenant.setLastUpdatedBy(currency.getLoginId());
        tenant.setLastUpdateDate(new Date());

        //修改租户信息
        tenantMapper.updateById(tenant);

        return Result.success();
    }

    /**
     * @Description: 批量删除租户信息
     * @author zhuliang
     * @date 2020/11/18 17:28
     */
    @Override
    public Result deleteTenant(String deleteId, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //拆分id
        String[] ids = deleteId.split(",");

        //根据id数组，批量删除
        tenantMapper.updateToDeleteById(currency.getLoginId(),
                                        new Date(),
                                        new Byte("1"),
                                        ids,
                                        currency.getProperty(),
                                        currency.getManagementOffice());

        return Result.success();
    }

    /**
     * @Description: 条件查询租户信息（带分页）
     * @author zhuliang
     * @date 2020/11/18 17:43
     */
    @Override
    public Result<List<CcmsSmartleasingTenant>> getAllTenantByCondition(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingTenant> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //开始分页条件查询
        List<CcmsSmartleasingTenant> tenantList = tenantMapper.getAllByCondition(queryCriteria.getTenantType(),
                                                                                queryCriteria.getFkBuildingId(),
                                                                                queryCriteria.getInputString(),
                                                                                queryCriteria.getContactPhone(),
                                                                                queryCriteria.getIdcardNumber(),
                                                                                queryCriteria.getContractNumber(),
                                                                                queryCriteria.getHouseNumber(),
                                                                                currency.getProperty(),
                                                                                currency.getManagementOffice(),
                                                                                toPage);

        return Result.success(tenantList, toPage.getTotal());
    }

    /**
     * @Description: 重置租户密码
     * @author zhuliang
     * @date 2021/1/7 19:00
     */
    @Override
    public Result resetPassword(String pkTenantId, String contactPhone, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //重置租户密码
        tenantMapper.resetPassword(new Date(), currency.getLoginId(), contactPhone.substring(contactPhone.length() - 6), pkTenantId, contactPhone);

        return Result.success();
    }
}
